/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.services;

import utsc.apps.utschedule.R;
import utsc.apps.utschedule.classes.Assignment;
import utsc.apps.utschedule.ui.activities.AssignmentDetailActivity;
import utsc.apps.utschedule.util.database.DatabaseManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;

/**
 * A service that sends notification for assignment that is due.
 */
public class NotifyService extends Service {

	public static final String FROM_NOTIFICATION="fromNotification";
	
	/**
     * Class for clients to access
     */
    public class ServiceBinder extends Binder {
        NotifyService getService() {
            return NotifyService.this;
        }
    }
 
    // Unique id to identify the notification.
    private static final int NOTIFICATION = 123;
    // Name of an intent extra we can use to identify if this service was started to create a notification  
    public static final String INTENT_NOTIFY = "utsc.apps.utschedule.services.INTENT_NOTIFY";
    // The system notification manager
    private NotificationManager _nM;
 
    @Override
    public void onCreate() {
        _nM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }
 
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //Log.i("LocalService", "Received start id " + startId + ": " + intent);
         
        // If this service was started by out AlarmTask intent then we want to show our notification
        if(intent.getBooleanExtra(INTENT_NOTIFY, false)){
            String[] intentIdentifier=intent.getDataString().split(":");
            int assignmentId=Integer.parseInt(intentIdentifier[1]);
            showNotification(assignmentId);
        }
        // We don't care if this service is stopped as we have already delivered our notification
        return START_NOT_STICKY;
    }
 
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
 
    // This is the object that receives interactions from clients
    private final IBinder mBinder = new ServiceBinder();
 
    /**
     * Creates a notification and shows it in the OS drag-down status bar
     */
    private void showNotification(int id) {
        // This is the icon to use on the notification
        int icon = R.drawable.ic_launcher;
        // What time to show on the notification
        long time = System.currentTimeMillis();
        Intent intent=new Intent(this, AssignmentDetailActivity.class);
        intent.putExtra(Assignment.ASSUID, id);
        intent.putExtra(FROM_NOTIFICATION, true);
        int requestCode=(int) (id+System.currentTimeMillis());
        
        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, requestCode, intent, Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
        Assignment assignment=DatabaseManager.getInstance(getApplicationContext()).getAssignment(id);
        if (assignment!=null) {
        	CharSequence title = "Assignment - Due in "+assignment.get_reminder()+" "+Assignment.REMINDER_UNIT[assignment.get_reminderUnit()];
        	// This is the scrolling text of the notification
            CharSequence text = assignment.get_Title()+" is due @ "+assignment.get_DueDate()+" "+assignment.get_DueTime()+ ".";  
        	Builder builder=new NotificationCompat.Builder(getApplicationContext());
            builder.setAutoCancel(true);
            builder.setContentText(text);
            builder.setContentTitle(title);
            builder.setSmallIcon(icon);
            builder.setContentInfo(text);
            builder.setContentIntent(contentIntent);
            builder.setWhen(time);
            
            Notification notification = builder.getNotification();
            
            // Set the info for the views that show in the notification panel.
            //notification.setLatestEventInfo(this, title, text, contentIntent);
     
            // Clear the notification when it is pressed
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notification.defaults |=Notification.DEFAULT_SOUND;
            notification.defaults |=Notification.DEFAULT_VIBRATE;
             
            // Send the notification to the system.
            _nM.notify(id+NOTIFICATION, notification);
             
		}
        // Stop the service when we are finished
        stopSelf();
    }

}
